using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.Media;

namespace WindowsPhoneGame3
{
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        int[,] map = new int[3, 3]; //khoi tao map gom 9 o
        Item[] item = new Item[9];
        private Texture2D bg;
        int luot = 1;       //khai bao luot di cua p1 or p2
        Computer computer;      
        Vector2 vitriComputer;  //vi tri cua may choi
        int mode;
        int trangthaiwin;
        bool isTask = false;
        bool isTask2 = false;
        int[,] bangdiem = new int[2, 3];
        public static int screen = 0;
        private Texture2D bg2;
        private Texture2D refresh;
        private Texture2D about;
        private Texture2D setting;
        private Texture2D exit;
        private Texture2D taskpark, taskbar, taskbar2;
        private Texture2D help;
        private Texture2D appinfor;
        GestureSample gesture;  //lay su kien bat cu chi
        SpriteFont font, font1;
        Song mysong;
        SoundEffect a, win, draw, lose;
        float volume = 1.0f;
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            // Frame rate is 30 fps by default for Windows Phone.
            TargetElapsedTime = TimeSpan.FromTicks(333333);

            // Extend battery life under lock.
            InactiveSleepTime = TimeSpan.FromSeconds(1);
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    map[i, j] = 0;  //khoi tao map trong-chua co nuoc di
                    item[i * 3 + j] = new Item();//khoi tao cac nuoc di
                }
            }
            for (int i = 0; i < 2; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    bangdiem[i, j] = 0; //khoi tao bang diem
                }
            }
            TouchPanel.EnabledGestures = GestureType.Tap;
            trangthaiwin = 0;
            computer = new Computer();
            base.Initialize(); //khoi tao cac doi tuong, new object 
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent() 
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    item[i * 3 + j].setloai(map[i, j]); //o trong = 0
                    item[i * 3 + j].setposition(i, j);  //vi tri cua cac o
                    item[i * 3 + j].LoadContent(this.Content);  //ve cac anh vao o
                }
            }
            bg = this.Content.Load<Texture2D>("images/background");
            bg2 = Content.Load<Texture2D>("images/background1");
            exit = Content.Load<Texture2D>("images/exit");
            refresh = Content.Load<Texture2D>("images/refresh");
            about = Content.Load<Texture2D>("images/about");
            setting = Content.Load<Texture2D>("images/setting");
            taskpark = Content.Load<Texture2D>("images/taskpark");
            appinfor = Content.Load<Texture2D>("images/appinfor");
            help = Content.Load<Texture2D>("images/help");
            taskbar = Content.Load<Texture2D>("images/taskbar2");
            taskbar2 = Content.Load<Texture2D>("images/bar2");
            mysong = Content.Load<Song>("sounds/backsound2");
            MediaPlayer.Play(mysong);
            MediaPlayer.IsRepeating=true;            
            a = Content.Load<SoundEffect>("sounds/Ball");
            win = Content.Load<SoundEffect>("sounds/win");
            draw = Content.Load<SoundEffect>("sounds/draw");
            lose = Content.Load<SoundEffect>("sounds/lose1");
            font = this.Content.Load<SpriteFont>("SpriteFont1");
            font1 = this.Content.Load<SpriteFont>("SpriteFont2");
            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here
            //man hinh help
            if (screen == 2)
            {
                if (TouchPanel.IsGestureAvailable)
                {
                    gesture = TouchPanel.ReadGesture();
                    Vector2 touch = gesture.Position;
                    if (touch.X >= 40 && touch.X <= 90 && touch.Y >= 60 && touch.Y <= 100)
                    {
                        screen = 0;
                    }

                }

            }
                //man hinh appinfo
            else if (screen == 3)
            {
                if (TouchPanel.IsGestureAvailable)
                {
                    gesture = TouchPanel.ReadGesture();
                    Vector2 touch = gesture.Position;
                    if (touch.X >= 40 && touch.X <= 90 && touch.Y >= 60 && touch.Y <= 100)
                    {
                        screen = 0;
                    }

                }
            }
            // man hinh bat dau game
            else if (screen == 0)
            {
                if (TouchPanel.IsGestureAvailable)
                {
                    gesture = TouchPanel.ReadGesture();
                    Touch();
                }
            }

            //man hinh choi game: 2p hoac 1p
            else if (screen == 1)
            {
                // xu ly su kien click chuot
                if (TouchPanel.IsGestureAvailable)
                {
                    gesture = TouchPanel.ReadGesture();//gan gesture la su kien touch
                    if (isTask2 == false)
                    {
                        if (gesture.GestureType == GestureType.Tap) //if: da cham touch 
                        {
                            if (trangthaiwin == 0) //va trang thai chua thang
                            {
                                for (int i = 0; i < 9; i++)
                                {
                                    if (item[i].isTouch(gesture.Position) && item[i].getloai() == 0)//kt touch va o ay chua dc danh
                                    {
                                        item[i].setloai(luot);  //set loai cua luot danh - mac dinh: luot X
                                        item[i].LoadContent(this.Content);  //ve hinh luot danh
                                        a.Play(volume, 0.0f, 0.0f);
                                        map[i / 3, i % 3] = luot;   //set gia tri cua moi o trong map la luot danh: 1 or 2

                                        if (isWinner())
                                        {
                                            trangthaiwin = luot;
                                            if (luot == 1)
                                            {
                                                bangdiem[0, 0]++;   //X win ++ cho nguoi X 
                                                bangdiem[1, 2]++;  //O lose ++ cho O
                                                //?? doi luot sau khi thang
                                            }
                                            else
                                            {
                                                bangdiem[1, 0]++;   //O win ++
                                                bangdiem[0, 2]++;   // X lose ++                                             
                                            }
                                            win.Play(volume, 0.0f, 0.0f);
                                        }
                                            //ham hoa cua 2P
                                        else if (isTie())
                                        {
                                            trangthaiwin = 3;
                                            bangdiem[0, 1]++;   //X draw ++
                                            bangdiem[1, 1]++;   //O draw ++
                                            draw.Play(volume, 0.0f, 0.0f);
                                        }
                                        //May choi
                                        else
                                        {
                                            //doi luot cho nguoi thu 2 danh
                                            turn();
                                            if (mode == 1)
                                            {
                                                computer.setmap(map);
                                                computer.Play();
                                                vitriComputer = computer.getViTri();
                                                map[(int)vitriComputer.X, (int)vitriComputer.Y] = luot;
                                                item[(int)vitriComputer.X * 3 + (int)vitriComputer.Y].setloai(luot);
                                                item[(int)vitriComputer.X * 3 + (int)vitriComputer.Y].LoadContent(this.Content);
                                                if (isWinner())
                                                {
                                                    trangthaiwin = luot;
                                                    bangdiem[0, 2]++;
                                                    lose.Play(volume, 0.0f, 0.0f);
                                                }
                                                    //Ham hoa cua 1P
                                                else if (isTie())
                                                {
                                                    trangthaiwin = 3;
                                                    bangdiem[0, 1]++;
                                                    draw.Play(volume, 0.0f, 0.0f);
                                                }
                                                //doi luot cho ban danh
                                                turn();
                                            }
                                        }
                                        break;
                                    }
                                }
                            }
                            if (gesture.Position.X < 250 || gesture.Position.X > 638 || gesture.Position.Y < 46 || gesture.Position.Y > 434)
                            {
                                if (gesture.Position.X >= 0 && gesture.Position.X <= 190 && gesture.Position.Y >= 0 && gesture.Position.Y <= 60)
                                {
                                    screen = 0;
                                    bangdiem[0, 0] = 0;
                                    bangdiem[0, 1] = 0;
                                    bangdiem[0, 2] = 0;
                                    bangdiem[1, 0] = 0;
                                    bangdiem[1, 1] = 0;
                                    bangdiem[1, 2] = 0;
                                    newmap();
                                }
                                if (gesture.Position.X >= 680 && gesture.Position.X <= 752 && gesture.Position.Y >= 204 && gesture.Position.Y <= 276)
                                {
                                    newmap();
                                }
                                else if (isTask2 == false)
                                {
                                    isTask2 = true;
                                }
                                else
                                {
                                    isTask2 = false;
                                }
                            }
                        }
                    }
                        //click taskbar
                    else
                    {
                        if (gesture.Position.X >= 190 && gesture.Position.X <= 230 && gesture.Position.Y >= 393 && gesture.Position.Y <= 453)
                        {
                            if (volume == 1)
                            {
                                volume = 0;
                                MediaPlayer.Stop();
                            }
                            else
                            {
                                volume = 1;
                                MediaPlayer.Play(mysong);
                            }
                        }
                        else if (gesture.Position.X >= 60 && gesture.Position.X <= 120 && gesture.Position.Y >= 393 && gesture.Position.Y <= 453)
                        {

                            bangdiem[0, 0] = 0;
                            bangdiem[0, 1] = 0;
                            bangdiem[0, 2] = 0;
                            bangdiem[1, 0] = 0;
                            bangdiem[1, 1] = 0;
                            bangdiem[1, 2] = 0;
                            newmap();
                            isTask2 = false;
                        }
                        else
                        {
                            isTask2 = false;
                        }
                    }
                }
            }

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here
            spriteBatch.Begin();

            //spriteBatch.Draw(bg, new Vector2(0, 0), Color.White);   //set background
            if (screen == 0)
            {
                if (isTask == false)
                {
                    spriteBatch.Draw(bg2, new Vector2(0, 0), Color.White);
                }
                if (isTask == true)
                {
                    spriteBatch.Draw(bg2, new Vector2(0, 0), Color.White);
                    spriteBatch.Draw(taskpark, new Vector2(0, 383), Color.White);
                }
            }
            //man hinh choi game
            if (screen == 1)
            {
                spriteBatch.Draw(bg, new Vector2(0, 0), Color.White);   //set background
                for (int i = 0; i < 9; i++)
                {
                    item[i].Draw(spriteBatch); 
                }

                if (mode == 1)
                {
                    //mode 1: 1 Play. 
                    spriteBatch.DrawString(font, " You", new Vector2(100, 130), Color.Blue);
                    spriteBatch.DrawString(font1, " Win: "+"       " + bangdiem[0, 0].ToString(), new Vector2(10, 200), Color.Blue);
                    spriteBatch.DrawString(font1, " Draw:"+"      " + bangdiem[0, 1].ToString(), new Vector2(10, 260), Color.Blue);
                    spriteBatch.DrawString(font1, " Lose:"+"       " + bangdiem[0, 2].ToString(), new Vector2(10, 320), Color.Blue);
                }
                else
                {
                    //mode 2: 2 Play.
                    spriteBatch.DrawString(font, "  X  O", new Vector2(90, 150), Color.Blue);
                    spriteBatch.DrawString(font1, " Win: "+"   "+ bangdiem[0, 0].ToString() +"    "+bangdiem[1, 0].ToString(), new Vector2(10, 210), Color.Blue);
                    spriteBatch.DrawString(font1, " Draw:"+"  "+ bangdiem[0, 1].ToString() + "    "+bangdiem[1, 1].ToString(), new Vector2(10, 270), Color.Blue);

                }
                //hien thi trang thai X win hoac You win
                if (trangthaiwin == 1)
                {
                    if (mode == 2)
                    {
                        spriteBatch.DrawString(font, " X Win !", new Vector2(20, 90), new Color(0, 255, 0)); 
                    }
                    else
                    {
                        spriteBatch.DrawString(font, "You Win!", new Vector2(10, 90), new Color(0, 255, 0));
                    }
                }
                //hien thi trang thai O win hoac Computer win
                if (trangthaiwin == 2)
                {
                    if (mode == 2)
                    {
                        spriteBatch.DrawString(font, " O Win !", new Vector2(20, 90), new Color(0, 255, 0));  
                    }
                    else
                    {
                        spriteBatch.DrawString(font, "You Lose", new Vector2(8, 75), new Color(0, 255, 0));
                    }
                }
                //hien thi trang thai hoa
                if (trangthaiwin == 3)
                {
                    spriteBatch.DrawString(font, " Draw !", new Vector2(20, 75), new Color(0, 255, 0));  
                }

                if (isTask2 == true)
                {
                    //hinh loa bat/tat
                    if (volume == 1)
                    {
                        spriteBatch.Draw(taskbar, new Vector2(0, 383), Color.White);
                    }
                    else
                    {
                        spriteBatch.Draw(taskbar2, new Vector2(0, 383), Color.White);
                    }
                }
                //hien thi hinh restart sau khi draw/win
                if (trangthaiwin != 0)
                {
                    spriteBatch.Draw(refresh, new Vector2(680, 204), Color.White);
                }
                else
                {
                    //mode2: 2play hien thi luot danh tiep theo
                    if (mode == 2)
                    {
                        spriteBatch.DrawString(font, "Turn", new Vector2(670, 154), Color.SteelBlue);                        
                        if (luot == 1)
                        {
                            spriteBatch.DrawString(font, "X", new Vector2(708, 224), Color.Gold);
                        }
                        else
                        {
                            spriteBatch.DrawString(font, "O", new Vector2(708, 224), Color.Gold);
                        }
                    }
                }
            }

            if (screen == 2)
            {
                spriteBatch.Draw(help, new Vector2(0, 0), Color.White);
            }
            if (screen == 3)
            {
                spriteBatch.Draw(appinfor, new Vector2(0, 0), Color.White);
            }
            spriteBatch.End();

            base.Draw(gameTime);
        }
        // ham doi luot
        public void turn()
        {
            if (luot == 1)
            {
                luot = 2;
            }
            else
            {
                luot = 1;
            }
        }

        public bool isWinner()
        {
            if (map[0, 0] == luot && map[0, 1] == luot && map[0, 2] == luot) return true;
            else if (map[0, 0] == luot && map[1, 0] == luot && map[2, 0] == luot) return true;
            else if (map[0, 0] == luot && map[1, 1] == luot && map[2, 2] == luot) return true;
            else if (map[1, 0] == luot && map[1, 1] == luot && map[1, 2] == luot) return true;
            else if (map[2, 0] == luot && map[2, 1] == luot && map[2, 2] == luot) return true;
            else if (map[0, 1] == luot && map[1, 1] == luot && map[2, 1] == luot) return true;
            else if (map[0, 2] == luot && map[1, 2] == luot && map[2, 2] == luot) return true;
            else if (map[0, 2] == luot && map[1, 1] == luot && map[2, 0] == luot) return true;
            else return false;
        }
        //Kiem tra co hoa khong

        public bool isTie()
        {
            for (int i = 0; i < 9; i++)
            {
                if (map[i / 3, i % 3] == 0)
                {
                    return false;
                }
            }
            return true;
        }
        public void Touch()
        {
            Vector2 touch = gesture.Position;
            //man hinh bat dau
            if (isTask == false)
            {
                //di vao man hinh choi 1 nguoi
                if (touch.X >= 252 && touch.X <= 541 && touch.Y >= 141 && touch.Y <= 218)
                {
                    screen = 1;
                    mode = 2;
                    isTask2 = false;
                }
                //di vao man hinh choi 2 nguoi
                else if (touch.X >= 252 && touch.X <= 541 && touch.Y >= 251 && touch.Y <= 330)
                {
                    screen = 1;
                    mode = 1;
                    isTask2 = false;
                }
                //bat tasbar
                else
                {
                    isTask = true;
                }
            }
            else
            {
                //vao appinfo
                if (touch.X >= 70 && touch.X <= 110 && touch.Y >= 393 && touch.Y <= 453)
                {
                    screen = 3;
                }
                //vao help
                else if (touch.X >= 190 && touch.X <= 250 && touch.Y >= 393 && touch.Y <= 453)
                {
                    screen = 2;
                }
                isTask = false;
            }
        }
        public void newmap()
        {
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    map[i, j] = 0;
                    item[i * 3 + j].setloai(0);
                    item[i * 3 + j].LoadContent(this.Content);                  
                    luot = 1;
                    trangthaiwin = 0;
                }
            }
        }
    }
}
